// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.datainterface.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.query.QueryGenerator;
import com.fowo.api.datainterface.entity.DatainterfaceAuthority;
import com.fowo.api.datainterface.mapper.DatainterfaceAuthorityMapper;
import com.fowo.api.datainterface.model.DatainterfaceAuthoritySearchParamPo;
import com.fowo.api.datainterface.model.DatainterfaceAuthorityVo;
import com.fowo.api.datainterface.service.DatainterfaceAuthorityService;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 接口认证 服务实现基类
 */
@Slf4j
@DS("ds21")
@Service
public class DatainterfaceAuthorityServiceImpl
        extends ServiceImpl<DatainterfaceAuthorityMapper, DatainterfaceAuthority>
        implements DatainterfaceAuthorityService {

    public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>();
    // 导出时单次查询最大记录数
    protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
    // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
    protected static final long EXPORT_MAX_SIZE = 1048575;

    @Resource
    protected FileService fileService;

    @Resource
    protected SysImportTemplateService importTemplateService;

    @Resource
    protected Validator validator;

    /**
     * 创建接口认证
     *
     * @param model 接口认证
     * @return 新数据的主键
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long create(DatainterfaceAuthorityVo model) throws Exception {
        JwtUserInfo currentUser = JwtUserInfo.fromHeader();
        DatainterfaceAuthority entity = new DatainterfaceAuthority();
        BeanUtils.copyProperties(model, entity);
        entity.setCreateTime(new Date());
        entity.setLastUpdateTime(new Date());
        if (currentUser != null) {
            entity.setCreateUser(currentUser.getUserId());
            entity.setLastUpdateUser(currentUser.getUserId());
        }
        entity.setAppCode(entity.getDataType());
        if (this.save(entity)) {
            return entity.getId();
        }
        throw new Exception("接口认证保存失败");
    }

    /**
     * 更新接口认证
     *
     * @param model 接口认证
     * @return 更新是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(DatainterfaceAuthorityVo model) throws Exception {
        JwtUserInfo currentUser = JwtUserInfo.fromHeader();
        DatainterfaceAuthority entity = this.getById(model.getId());
        if (entity == null) {
            throw new Exception("接口认证不存在");
        }
        BeanUtils.copyProperties(
                model,
                entity,
                "id",
                "createTime",
                "createUser",
                "lastUpdateTime",
                "lastUpdateUser"
        );
        entity.setLastUpdateTime(new Date());
        if (currentUser != null) {
            entity.setLastUpdateUser(currentUser.getUserId());
        }
        if (this.updateById(entity)) {
            return true;
        }
        return false;
    }

    /**
     * 更新接口认证（带空值）
     *
     * @param model 接口认证
     * @return 更新是否成功
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateForEdit(DatainterfaceAuthorityVo model)
            throws Exception {
        JwtUserInfo currentUser = JwtUserInfo.fromHeader();
        DatainterfaceAuthority entity = this.getById(model.getId());
        if (entity == null) {
            throw new Exception("接口认证不存在");
        }
        model.setLastUpdateTime(new Date());
        if (currentUser != null) {
            model.setLastUpdateUser(currentUser.getUserId());
        }
        boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
                .set(DatainterfaceAuthority::getLastUpdateTime, model.getLastUpdateTime())
                .set(DatainterfaceAuthority::getLastUpdateUser, model.getLastUpdateUser())
                .set(DatainterfaceAuthority::getAppCode, model.getAppCode())
                .set(DatainterfaceAuthority::getAppName, model.getAppName())
                .set(DatainterfaceAuthority::getAppAuthInfo, model.getAppAuthInfo())
                .set(DatainterfaceAuthority::getRootPath, model.getRootPath())
                .set(
                        DatainterfaceAuthority::getVerifySignature,
                        model.getVerifySignature()
                )
                .set(DatainterfaceAuthority::getUserfulLife, model.getUserfulLife())
                .set(DatainterfaceAuthority::getEnableMark, model.getEnableMark())
                .set(DatainterfaceAuthority::getDescriptions, model.getDescriptions())
                .set(DatainterfaceAuthority::getGroupCode, model.getGroupCode())
                .set(DatainterfaceAuthority::getDataType, model.getDataType())
                .eq(DatainterfaceAuthority::getId, model.getId())
                .update();
        if (isOk) {
        }
        return isOk;
    }

    /**
     * 删除接口认证
     *
     * @param id 接口认证的主键
     * @return 删除是否成功
     */
    @Override
    public boolean delete(Long id) throws Exception {
        return this.removeById(id);
    }

    /**
     * 批量删除接口认证
     *
     * @param ids 接口认证的主键列表
     * @return 删除是否成功
     */
    @Override
    public boolean batchDelete(List<Long> ids) throws Exception {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 获取详情
     *
     * @param id 接口认证的主键
     */
    @Override
    public DatainterfaceAuthorityVo getVoById(Long id) throws Exception {
        DatainterfaceAuthority vo = this.getById(id);
        if (vo == null) {
            return null;
        }
        return BeanUtil.copyProperties(vo, DatainterfaceAuthorityVo.class);
    }

    /**
     * 分页查询接口认证
     *
     * @param search 查询条件
     * @return 接口认证分页查询结果
     */
    @Override
    public Page<DatainterfaceAuthority> pageSearch(
            DatainterfaceAuthoritySearchParamPo search
    ) {
        DatainterfaceAuthority datainterfaceAuthority = BeanUtil.copyProperties(search, DatainterfaceAuthority.class);
        QueryWrapper<DatainterfaceAuthority> queryWrapper = QueryGenerator.initQueryWrapper(datainterfaceAuthority, search);
        Page<DatainterfaceAuthority> pageList = this.page(search.toPage(), queryWrapper);
        return pageList;
    }

    /**
     * 通过删除标记查询数据接口调用日志主键(重复时返回最新的主键)
     */
    @Override
    public Long getIdByDelFlag(String delFlag) {
        return this.getObj(Wrappers.<DatainterfaceAuthority>lambdaQuery().select(DatainterfaceAuthority::getId).eq(DatainterfaceAuthority::getDelFlag, delFlag), res -> Convert.toLong(res));
    }

    /**
     * 通过删除标记查询数据接口调用日志多主键(重复时返回最新的主键)
     */
    @Override
    public List<Long> getIdsByDelFlag(List<String> list) {
        return this.listObjs(Wrappers.<DatainterfaceAuthority>lambdaQuery().select(DatainterfaceAuthority::getId).in(DatainterfaceAuthority::getDelFlag, list), res -> Convert.toLong(res));
    }

    /**
     * 通过数据接口调用日志主键查询删除标记
     */
    @Override
    public String getDelFlagById(Long id) {
        return this.getObj(Wrappers.<DatainterfaceAuthority>lambdaQuery().select(DatainterfaceAuthority::getDelFlag).eq(DatainterfaceAuthority::getId, id), res -> Convert.toStr(res));
    }

    /**
     * 通过数据接口调用日志主键查询删除标记列表
     */
    @Override
    public List<String> getDelFlagByIds(List<Long> ids) {
        return this.listObjs(Wrappers.<DatainterfaceAuthority>lambdaQuery().select(DatainterfaceAuthority::getDelFlag).in(DatainterfaceAuthority::getId, ids), res -> Convert.toStr(res));
    }

    /**
     * 列表查询接口认证
     *
     * @param search 查询条件
     * @return 接口认证列表查询结果
     */
    @Override
    public List<DatainterfaceAuthority> search(
            DatainterfaceAuthoritySearchParamPo search
    ) {
        DatainterfaceAuthority datainterfaceAuthority = BeanUtil.copyProperties(search, DatainterfaceAuthority.class);
        QueryWrapper<DatainterfaceAuthority> queryWrapper = QueryGenerator.initQueryWrapper(datainterfaceAuthority, search);
        return this.list(queryWrapper);
    }

    /**
     * 查询接口认证最后更新时间
     *
     * @param search 查询条件
     * @return 接口认证最后更新时间
     */
    @Override
    public Date searchLastUpdateTime(DatainterfaceAuthoritySearchParamPo search) {
        DatainterfaceAuthority datainterfaceAuthority = BeanUtil.copyProperties(search, DatainterfaceAuthority.class);
        QueryWrapper<DatainterfaceAuthority> queryWrapper = QueryGenerator.initQueryWrapper(datainterfaceAuthority, search, null, null);
        queryWrapper.select("max(last_update_time) last_update_time");
        return this.getObj(queryWrapper, res -> Convert.toDate(res));
    }
}
